import 'dart:core';
import 'dart:developer';
import 'package:flutter/material.dart';
import 'package:flutter/widgets.dart';
void main() {
  runApp(MaterialApp(home: TextHomePage()));
}

class Yjhconter extends InheritedWidget{
  //1.共享的数据
  final int count;
  //2.构造方法
  Yjhconter({required this.count,required Widget child}):super(child: child);
  //3.获取当前最近的Inherited对象
  static Yjhconter? of(BuildContext context){
    //沿着element树，去找到最近的YjhconterElement，从Element中取出Widget对象
    return context.dependOnInheritedWidgetOfExactType<Yjhconter>();
  }
  // 决定要不要回调State中的didchangeDependencies
  // 如果返回true：执行当前的InheritedWidget的State中的didchangeDependcies
  @override
  bool updateShouldNotify(Yjhconter oldWidget) {
    return oldWidget.count != this.count;
  }
}
class TextHomePage extends StatefulWidget {
  @override
  State<StatefulWidget> createState() {
    return TextHomePageState();
  }
}

class TextHomePageState extends State<TextHomePage> {
  int _counter =100;
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
        home: Scaffold(
          appBar: AppBar(
            title: const Text("listview"),
          ),
          body:Yjhconter(
            count: _counter,
            child: Column(
              children: const [
                Yjhshowdata01(),
                Yjhshowdata02()],
            ),
          ),
          floatingActionButton: FloatingActionButton(
            onPressed: () {
              setState(() {
                _counter =_counter+1;
                print(_counter);
                print(Yjhconter.of(context)?.count);
              });
            },
            child: Icon(Icons.add),
          ),
        )
    );
  }
}
//
class Yjhshowdata01 extends StatelessWidget {
  const Yjhshowdata01({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    int? count = Yjhconter.of(context)?.count;
    return Card(
      color: Colors.green,
      child: Text("当前计数:${count}"),
    );
  }
}
//
class Yjhshowdata02  extends StatelessWidget {
  const Yjhshowdata02 ({Key? key}) : super(key: key);
  @override
  Widget build(BuildContext context) {
    int? count = Yjhconter.of(context)?.count;
    return Container(
      color: Colors.blue,
      child: Text("当前计数:${count}"),
    );
  }
}



